import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import '../../../core/utils/show_toast.dart';
import '../../../data/controllers/auth_controller.dart';
import '../../../data/models/auth/user.dart';
import '../../dashboard_container_screen/dashboard_container_screen.dart';
import '/core/app_export.dart';
part 'login_event.dart';
part 'login_state.dart';



enum LoginStatus { initial, success, error, loading , invalidData }

extension LoginStatusX on LoginStatus {
  bool get isInitial => this == LoginStatus.initial;
  bool get isSuccess => this == LoginStatus.success;
  bool get isError => this == LoginStatus.error;
  bool get isLoading => this == LoginStatus.loading;
  bool get invalidData => this == LoginStatus.invalidData;
}


/// A bloc that manages the state of a Login according to the event that is dispatched to it.
class LoginBloc extends Bloc<LoginEvent, LoginState> {
  LoginBloc(LoginState initialState) : super(initialState) {
    on<LoginInitialEvent>(_onInitialize);
    on<LoginOnTapLoginEvent>(_login);
  }

  _onInitialize(
    LoginInitialEvent event,
    Emitter<LoginState> emit,
  ) async {
    emit(state.copyWith(
        emailController: TextEditingController(),
        passwordController: TextEditingController()));
  }


  _login(
      LoginOnTapLoginEvent event,
      Emitter<LoginState> emit,
      ) async {
    emit(state.copyWith(status: LoginStatus.loading));
    await AuthController.login(
       usernameOrEmail: state.emailController?.text.trim(),
        password: state.passwordController?.text.trim(),
        barcode: state.barcode
    ).catchError((e){
      print(e);
      emit(state.copyWith(status: LoginStatus.error));
      return null;
    }).then((value){
      if(value != null && value.state) {
        var user = User.fromJson(value.data);
        PrefUtils.saveUserData(user);
        emit(state.copyWith(status: LoginStatus.success , user: user));
      }else if(value != null){
        showMessage(value.message);
        emit(state.copyWith(status: LoginStatus.invalidData));
      }else{
        showMessage('عذراً حدث خطأ ما الرجاء المحاولة لاحقاً');
        emit(state.copyWith(status: LoginStatus.error));
        print('value is null');
      }
    });
  }



}
